﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoProcessService.Interface;
using System.Security.Cryptography;
using System.Net;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using AutoProcessSerivce.Library.WorkPool.WorkPool;
using AutoProcessSerivce.Library.WorkPool.WorkPool.WorkHandle.Email;

namespace AutoCheckTradeStatus
{
    public class Executor : IAutoProcess
    {
        private string password = "lunwenyun@chongshantech@20!#";
        public Executor()
        {
            Interval = 12;
        }

        public override void Execute(DateTime handleTime)
        {
            if (handleTime.Hour == 1) //凌晨1点
            {
                LogHelper.Write(CommonLogger.AutoCheckTradeStatus, LogLevel.Info,
                          String.Format("AutoCheckTradeStatus 于{0}开始执行。", handleTime.ToString()));


                List<Trade> trades = new List<Trade>();
                using (MySqlConnection con = new MySqlConnection("DataSource=121.199.62.134;DataBase=lunwenyun;uid=root;pwd=root@!#$;characterset=utf8;"))
                {
                    int id = 0;
                    while (true)
                    {
                        bool any = false;
                        MySqlCommand com = con.CreateCommand();
                        com.CommandText = String.Format("select * from t_trade where id>{0} and status={1} and isdelete=false limit 25",
                            id, 5);
                        com.CommandType = System.Data.CommandType.Text;
                        if (con.State != System.Data.ConnectionState.Open)
                        {
                            con.Open();
                        }
                        MySqlDataReader dr = com.ExecuteReader();
                        while (dr.Read())
                        {
                            if (!any)
                            {
                                any = true;
                            }
                            Trade trade = new Trade();
                            trade.ArticleId = getInt(dr["ArticleId"]);
                            trade.ConfirmExpireDate = getDatetime(dr["ConfirmExpireDate"]);
                            trade.ConfirmTradeDate = getDatetime(dr["ConfirmTradeDate"]);
                            trade.Consumer = getString(dr["Consumer"]);
                            trade.Description = getString(dr["Description"]);
                            trade.Id = getInt(dr["Id"]);
                            trade.IsDelete = getString(dr["IsDelete"]) == "1";
                            trade.LastModify = getDatetime(dr["LastModify"]);
                            trade.Momey = getDecimal(dr["Momey"]);
                            trade.OpenDate = getDatetime(dr["OpenDate"]);
                            trade.OpenUsername = getString(dr["OpenUsername"]);
                            trade.PeriodicalId = getInt(dr["PeriodicalId"]);
                            trade.Status = getInt(dr["Status"]);
                            trade.Supplier = getString(dr["Supplier"]);
                            trade.Token = getString(dr["Token"]);
                            trade.TradingDate = getDatetime(dr["TradingDate"]);
                            trades.Add(trade);
                        }
                        dr.Close();
                        if (!any)
                        {
                            break;
                        }
                        else
                        {
                            id = trades.Last().Id;
                        }
                    }
                }
                if (trades.Any())
                {
                    foreach (var item in trades)
                    {
                        if (item.ConfirmExpireDate < DateTime.Now)
                        {
                            using (MySqlConnection con = new MySqlConnection("DataSource=121.199.62.134;DataBase=lunwenyun;uid=root;pwd=root@!#$;characterset=utf8;"))
                            {
                                MySqlCommand com = con.CreateCommand();
                                com.CommandText = String.Format("insert into t_tradehistory(TradeId,PreStatus,NxtStatus,Remark,RecordDate,Operator) values({0},{1},{2},'{3}','{4}','{5}')",
                                    item.Id, item.Status, 7, "发表确认超时，自动确认完成", DateTime.Now, "auto check");
                                com.CommandType = System.Data.CommandType.Text;
                                con.Open();
                                com.ExecuteNonQuery();

                                com = con.CreateCommand();
                                com.CommandText = String.Format("update t_trade set status={0},LastModify='{1}',Token='{2}' where id={3}",
                                    7, DateTime.Now, Guid.NewGuid().ToString(),item.Id);
                                com.CommandType = System.Data.CommandType.Text;
                                com.ExecuteNonQuery();
                            }
                            
                            string toAgent = BuildTradeIsConfirmNotice_Auto(item);
                            if (!String.IsNullOrEmpty(toAgent))
                            {
                                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                               new NormalNotifyEmail()
                                               {
                                                   Message = toAgent,
                                                   Title = "您的稿件已自动被认定为发表成功 -- 学术论文云平台",
                                                   Recipient = item.Consumer
                                               });
                            }
                        }
                        else
                        {
                            string toAgent = BuildTradeWaitConfirmNotice_Auto(item);
                            if (!String.IsNullOrEmpty(toAgent))
                            {
                                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                               new NormalNotifyEmail()
                                               {
                                                   Message = toAgent,
                                                   Title = "您的稿件需要确认是否已经发表成功 -- 学术论文云平台",
                                                   Recipient = item.Consumer
                                               });
                            }
                        }
                    }
                }
                LogHelper.Write(CommonLogger.AutoCheckTradeStatus, LogLevel.Info, "定时任务【AutoCheckTradeStatus.dll】共执行" + trades.Count + "条记录");
            }
        }

        private int getInt(object o)
        {
            if (o == null)
            {
                return 0;
            }
            int i = 0;
            if (Int32.TryParse(o.ToString(), out i))
            {
                return i;
            }
            return 0;
        }
        private DateTime getDatetime(object o)
        {
            if (o == null)
            {
                return DateTime.MinValue;
            }
            DateTime dt = DateTime.MinValue;
            DateTime.TryParse(o.ToString(), out dt);
            return dt;
        }
        private string getString(object o)
        {
            if (o == null)
            {
                return string.Empty;
            }
            return o.ToString();
        }
        private decimal getDecimal(object o)
        {
            if (o == null)
            {
                return 0;
            }
            decimal d = 0;
            decimal.TryParse(o.ToString(),out d);
            return d;
        }
        private string BuildTradeIsConfirmNotice_Auto(Trade trade)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<style type=\"text/css\">");
            sb.AppendLine(".content{margin-left: auto;margin-right: auto;width: 700px;margin-top: 20px;line-height:160%;}");
            sb.AppendLine(".content-line{overflow: hidden;width: 100%;}");
            sb.AppendLine(".content-line-left{float: left;overflow: hidden;}");
            sb.AppendLine(".content-line-right{float: right;}");
            sb.AppendLine(".content-line-vspace{float: left;width: 15px;overflow: hidden;height: 1px;}");
            sb.AppendLine(".content-logo{}");
            sb.AppendLine(".content-topright{margin-top: 35px;margin-right: 5px;}");
            sb.AppendLine(".content-topright a{color: #333;text-decoration: none;}");
            sb.AppendLine(".content-topright span{color: #E1E1E1;padding: 0 5px;}");
            sb.AppendLine(".hline{overflow: hidden;height: 15px;width: 100%;margin-top: 4px;border-top: 1px solid #fafafa;}");
            sb.AppendLine(".content-toprighttext{padding-top: 15px;}");
            sb.AppendLine(".box{overflow: hidden;margin-left: auto;margin-right: auto;border-right: 1px solid #F0F6FA;border-bottom: 1px solid #F0F6FA;padding: 0 1px 1px 0;background-color: #E0ECF5;color: #4f4e4e;	padding-bottom: 1px;padding-right:1px;}");
            sb.AppendLine(".boxbg{background-color: #F9FCFD;border: 1px solid #BDC8D9;padding-left:20px;padding-right:20px;padding-top:10px;padding-bottom:20px;}");
            sb.AppendLine(".box-title{padding: 15px 10px 5px 10px;border-bottom: 1px solid #F3F3F3;margin-bottom: 5px;}");
            sb.AppendLine(".box-line{overflow: hidden;padding: 5px 10px 5px 10px;}");
            sb.AppendLine(".box-dotline{overflow: hidden;width: 755px;height: 5px;border-bottom: dotted 1px #b3b5b5;margin-left: auto;margin-right: auto;}");
            sb.AppendLine(".content-footer{border-top: 1px solid #F3F3F3;line-height: 1.8em;padding: 18px 0;color: #999;clear: both;margin-top: 20px;font-size:13px;}");
            sb.AppendLine(".content-footer-left{float: left;}");
            sb.AppendLine(".content-footer-left span{color: #999;padding: 0 5px;}");
            sb.AppendLine(".content-footer-left a{color: #666;text-decoration: none;}");
            sb.AppendLine(".content-footer-right{float: right;text-align: right;}");
            sb.AppendLine("</style>");
            sb.AppendLine("<div class=\"content\"><div class=\"content-line\"><div class=\"content-line-left\"><div class=\"content-logo\">");
            sb.AppendLine("<img src=\"http://www.lunwenyun.com/content/img/logo2.png\" /></div>");
            sb.AppendLine("</div><div class=\"content-line-right\"><div class=\"content-toprighttext\"></div>");
            sb.AppendLine("</div></div><div class=\"hline\"></div><div class=\"content-line\"><div class=\"box\"><div class=\"boxbg\">");
            sb.AppendLine("<p>您好！</p>");
            sb.AppendLine(String.Format("<p>您有一份论文约稿由于您未在规定时间内确认，已被系统自动认定为发表成功。如您有任何问题请登陆<a href=\"http://{0}\">{1}</a>并联系约稿人咨询或向管理员询问！</p>",
                "www.lunwenyun.com", "学术论文云平台"));
            sb.AppendLine("<p>本次约稿合约为：" + trade.Description + " <br/> </p>");
            sb.AppendLine("</div></div></div><div class=\"content-line\"><div class=\"content-footer\"><div class=\"content-footer-left\">");
            sb.AppendLine("<a href=\"http://www.lunwenyun.com/home/about\" target=\"_blank\">关于我们</a><span>|</span><a href=\"http://www.lunwenyun.com/home/contact\" target=\"_blank\">联系我们</a><span>|</span>");
            sb.AppendLine("<a href=\"http://www.lunwenyun.com/home/business\" target=\"_blank\">商务合作</a><span>|</span>");
            sb.AppendLine("</div></div></div></div>");
            return sb.ToString();
        }

        private string BuildTradeWaitConfirmNotice_Auto(Trade trade)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<style type=\"text/css\">");
            sb.AppendLine(".content{margin-left: auto;margin-right: auto;width: 700px;margin-top: 20px;line-height:160%;}");
            sb.AppendLine(".content-line{overflow: hidden;width: 100%;}");
            sb.AppendLine(".content-line-left{float: left;overflow: hidden;}");
            sb.AppendLine(".content-line-right{float: right;}");
            sb.AppendLine(".content-line-vspace{float: left;width: 15px;overflow: hidden;height: 1px;}");
            sb.AppendLine(".content-logo{}");
            sb.AppendLine(".content-topright{margin-top: 35px;margin-right: 5px;}");
            sb.AppendLine(".content-topright a{color: #333;text-decoration: none;}");
            sb.AppendLine(".content-topright span{color: #E1E1E1;padding: 0 5px;}");
            sb.AppendLine(".hline{overflow: hidden;height: 15px;width: 100%;margin-top: 4px;border-top: 1px solid #fafafa;}");
            sb.AppendLine(".content-toprighttext{padding-top: 15px;}");
            sb.AppendLine(".box{overflow: hidden;margin-left: auto;margin-right: auto;border-right: 1px solid #F0F6FA;border-bottom: 1px solid #F0F6FA;padding: 0 1px 1px 0;background-color: #E0ECF5;color: #4f4e4e;	padding-bottom: 1px;padding-right:1px;}");
            sb.AppendLine(".boxbg{background-color: #F9FCFD;border: 1px solid #BDC8D9;padding-left:20px;padding-right:20px;padding-top:10px;padding-bottom:20px;}");
            sb.AppendLine(".box-title{padding: 15px 10px 5px 10px;border-bottom: 1px solid #F3F3F3;margin-bottom: 5px;}");
            sb.AppendLine(".box-line{overflow: hidden;padding: 5px 10px 5px 10px;}");
            sb.AppendLine(".box-dotline{overflow: hidden;width: 755px;height: 5px;border-bottom: dotted 1px #b3b5b5;margin-left: auto;margin-right: auto;}");
            sb.AppendLine(".content-footer{border-top: 1px solid #F3F3F3;line-height: 1.8em;padding: 18px 0;color: #999;clear: both;margin-top: 20px;font-size:13px;}");
            sb.AppendLine(".content-footer-left{float: left;}");
            sb.AppendLine(".content-footer-left span{color: #999;padding: 0 5px;}");
            sb.AppendLine(".content-footer-left a{color: #666;text-decoration: none;}");
            sb.AppendLine(".content-footer-right{float: right;text-align: right;}");
            sb.AppendLine("</style>");
            sb.AppendLine("<div class=\"content\"><div class=\"content-line\"><div class=\"content-line-left\"><div class=\"content-logo\">");
            sb.AppendLine("<img src=\"http://www.lunwenyun.com/content/img/logo2.png\" /></div>");
            sb.AppendLine("</div><div class=\"content-line-right\"><div class=\"content-toprighttext\"></div>");
            sb.AppendLine("</div></div><div class=\"hline\"></div><div class=\"content-line\"><div class=\"box\"><div class=\"boxbg\">");
            sb.AppendLine("<p>您好！</p>");
            sb.AppendLine(String.Format("<p>您有一份论文约稿需要您确认是否已经成功发表，请在{0}之前登陆<a href=\"http://{1}\">{2}</a>确认或联系约稿人咨询，如有其它问题也可以联系管理员协助处理！</p>",
                trade.ConfirmExpireDate.ToString("yyyy-MM-dd HH:mm"), "www.lunwenyun.com", "学术论文云平台"));
            sb.AppendLine("<p>本次约稿合约为：" + trade.Description + " </p>");
            sb.AppendLine("</div></div></div><div class=\"content-line\"><div class=\"content-footer\"><div class=\"content-footer-left\">");
            sb.AppendLine("<a href=\"http://www.lunwenyun.com/home/about\" target=\"_blank\">关于我们</a><span>|</span><a href=\"http://www.lunwenyun.com/home/contact\" target=\"_blank\">联系我们</a><span>|</span>");
            sb.AppendLine("<a href=\"http://www.lunwenyun.com/home/business\" target=\"_blank\">商务合作</a><span>|</span><br/>");
            sb.AppendLine("</div></div></div></div>");
            return sb.ToString();
        }
    }
}
